package com.zero.config.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Set;

@SpringBootApplication
@EnableScheduling
public class SpringcloudConfigClientApplication {


	/**
	 * 定时Refresh远程仓库，同步config信息
	 */
	public final ContextRefresher contextRefresher;

	private final Environment environment;

	@Autowired
	public SpringcloudConfigClientApplication(ContextRefresher contextRefresher, Environment environment){
		this.contextRefresher = contextRefresher;
		this.environment = environment;
	}

	public static void main(String[] args) {
		SpringApplication.run(SpringcloudConfigClientApplication.class, args);
	}

	@Scheduled(fixedRate=5 * 1000,initialDelay = 3 * 1000)
	public void autoRefresh() {
		System.out.printf("定时器执行...");
       //contextRefresher上下文刷新器
		Set<String> updatedPropertyNames = contextRefresher.refresh();
		updatedPropertyNames.forEach(propertyName -> System.out.printf("[Thread :%s]  当前配置已更新，" +
						"具体Keys: %s ,Value: %s \n",
				Thread.currentThread().getName(),
				propertyName,
				environment.getProperty(propertyName)));
	}

	@Bean
	public MyHealthIndicator myHealthIndicator(){

		return  new MyHealthIndicator();
	}

	private class MyHealthIndicator implements HealthIndicator{

		@Override
		public Health health() {
			Health.Builder builder = Health.status(Status.UP);
			builder.withDetail("name","MyHealthIndicator");
			builder.withDetail("time",System.currentTimeMillis());
			return builder.build();
		}
	}
}
